<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OAAdmin;
use App\Model\OALimit;
use App\Model\OALogin;
use App\Model\OAProjectLx;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminLogic extends Controller
{
    //上班时间
    protected $work_time = [
        'work_start'=>'  09:00:00',
        'work_stop'=>'  18:00:00',
    ];
    protected $company_id = 5;//综合事业部
    //状态
    protected $state_list = ['备审','待审','已审'];

    protected $adminType = [
        3=>'休假申请',
        4=>'行政申请',
        5=>'加班申请',
        6=>'用车申请',
        7=>'考勤申请',
        8=>'物料申请',
        9=>'交通申请',
    ];

    protected function getSignStatus($start,$end){
        $date = date('Y-m-d');
        $timestamp = date('Y-m-d H:i:s');
    }

    //添加签到
    public function addSignIn($input)
    {
        $date = date('Y-m-d');
        $timestamp = date('Y-m-d H:i:s');
        $ip = get_real_ip();
        $desc = $input['desc'];
        $isExists = OALogin::query()
            ->where('uid',$input['uid'])
            ->where('date',$date)
            ->whereNotNull('start')
            ->whereNotNull('stop')
            ->exists();
        if($isExists) throw new \Exception('请勿重复签到');

        $login = OALogin::query()->where('uid',$input['uid'])->where('date',$date)->first();
        if(!is_null($login)){
            $time1 = strtotime($timestamp);
            $tim2 = strtotime($date . $this->work_time['work_stop']);
            $state = $time1 - $tim2 > 0 ? 1 : 3;//3:早退
            $login->erole = $input['roleid'];
            $login->stop = $timestamp;
            $login->edesc = $desc;
            $login->eip = $ip;
            $login->state_stop = $state;
            $login->save();
        }else{
            $time1 = strtotime($timestamp);
            $tim2 = strtotime($date . $this->work_time['work_start']);
            $state = $time1 - $tim2 > 0 ? 2 : 1;//1:正常;2:迟到
            $loginData = [
                'srole'=>$input['roleid'],
                'uid'=>$input['uid'],
                'start'=>$timestamp,
                'date'=>$date,
                'sdesc'=>$desc,
                'sip'=>$ip,
                'state_start'=>$state,
            ];
            OALogin::query()->insertGetId($loginData);
        }
    }

    //添加报销
    public function addAdminWork($params)
    {
        try {
            DB::beginTransaction();
            $roleid = $params['roleid'];
            $type = $params['type'];
            $adminWork = config('oa.adminWork');

            if(in_array($type,[4,3])){
                $work_id = $this->getWorkId($params['type'], $roleid);
                $approve_list = $this->getRoleMapCompany($work_id,$this->company_id);
            }else{
                $work_id = $adminWork[$type]['work_id'];
                $approve_list = $this->getRoleMapCompany($work_id,0,$params['xmid']);
            }

            $is_save = $params['is_save'];
            $roleList = $this->getRoleListByWorkId($work_id);

            $date = $params['date'] ?? date('Y-m-d');
            $start = is_array($date) ? $date[0] : $date;
            $end = is_array($date) ? $date[1] : null;
            $baoxiao_data = [
                'uid'=>$params['uid'],
                'xmid'=>$params['xmid'] ?? 0,
                'create_role'=>$params['roleid'],
                'title'=>$params['title'],
                'desc'=>$params['desc'],
                'money'=>isset($params['money']) ? resetMoney($params['money']) : 0,
                'type'=>$params['type'],
                'start'=>$start,
                'stop'=>$end,
                'work_id'=>$work_id,
                'role_list'=>implode(',',$roleList),
                'approver'=>$approve_list,
                'created_at'=>date('Y-m-d H:i:s'),
                'people_num'=> $params['peopleNum'] ?? 0,
                'tracffic_from'=>$params['tracfficFrom'] ?? '',
                'tracffic_to'=>$params['tracfficTo'] ?? '',
                'tracffic_type'=>$params['car_type'] ?? 0,
                'tracffic_area'=>$params['date_type'] ?? 0,
                'is_save'=>$is_save,

            ];
            $currentNode = $this->getCurrentNode($work_id,$roleid);
            $baoxiao_data['node_id'] = $currentNode;
            $baoxiao_data['roleid'] = $roleid;

            if(!$is_save){
                $nextApprove = $this->getNextApprover($currentNode,$work_id,1,$params['roleid']);
                $baoxiao_data['node_id'] = $nextApprove['node_id'];
                $baoxiao_data['roleid'] = $nextApprove['roleid'];
            }

            $limit_money = OALimit::getLimitMoney();
            if($baoxiao_data['money'] > $limit_money) throw new \Exception('报销金额'.$baoxiao_data['money'].'超出报销限额'.$limit_money);

            $bid = OAAdmin::query()->insertGetId($baoxiao_data);

            if(!empty($params['fileList'])) $this->saveFileList($bid,$params['fileList'],FILE_XZ,$work_id);

            DB::commit();

            return true;

        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //报销列表
    public function baoXiaoList($params)
    {
        $query = OAAdmin::query();
        $state = $params['state'];
        $roleid = $params['roleid'];
        $uid = $params['uid'];
        $isAdmin = $this->isAdmin($roleid);
        if($isAdmin){
            $query->where('status',$state);
        }else{
            $isCompanyRole = $this->isCompanyApprover($roleid);
            $query->whereRaw("FIND_IN_SET ('{$roleid}',`role_list`)");//哪些角色可以看
            if($isCompanyRole) $query->whereRaw("FIND_IN_SET ('{$uid}',`approver`)");
            else $query->where('create_role',$roleid)->where('uid',$uid);
            switch ($state){
                case 1://待审
                    $query->where('status',1);
                    break;
                case 2://已审
                    $query->where('status',2)->where('roleid','');
                    break;
                default://备审
                    $query->where('roleid',$roleid);
            }
        }
        //标题
        if(isset($params['title']) && !empty($params['title'])) $query->where('title','like',"%{$params['title']}%");
        //最小金额
        if(isset($params['money_min']) && !empty($params['money_min'])) $query->where('money','>=',$params['money_min']);
        //最大金额
        if(isset($params['money_max']) && !empty($params['money_max'])) $query->where('money','<=',$params['money_max']);
        //创建日期
        if(isset($params['date']) && !empty($params['date'])) $query->whereBetween('created_at',$params['date']);
        //类型
        if(isset($params['type']) && !empty($params['type'])) $query->where('type',$params['type']);

        $list = $query->orderBy('updated_at','DESC')->paginate($params['page_size'],['id','xmid','title','money','created_at','uid','type'])->toArray();

        $list['admin_type_list'] = $this->adminType;
        $list['state_list'] = $this->state_list;
        if(empty($list['data'])) return $list;
        $common = (new CommonLogic())->getCommonData(['staff']);
        $staff_list = $common['staff'];
        $staff_list = array_column($staff_list,'username','id');
        foreach ($list['data'] as &$val){
            $val['username'] = $staff_list[$val['uid']];
            $project_name = OAProjectLx::query()->where('id',$val['xmid'])->value('name');
            $val['project_name'] = $project_name ?? '无';
            $val['type'] = $this->adminType[$val['type']];
        }
        return $list;
    }

    //获取可申请的行政项目
    public function getApplyList($input)
    {
       $list =  OAProjectLx::query()->where([
           'create_role'=>$input['roleid'],
           'uid'=>$input['uid'],
           'status'=>2])
           ->select(['id','name'])
           ->get()
           ->toArray();
       return empty($list) ? [['id'=>0,'name'=>'无']]  : $list;
    }

    //获取行政详情
    public function getAdminDetail($params)
    {
        try {
            $id = $params['id'];
            $info = OAAdmin::query()->where('id', $id)->first();
            $info->baseinfo = $info->xmid ? $this->getBaseInfo(['id' => $info->xmid]) : [];
            $info->gsid = $info->xmid ? $info->baseinfo->gsid : $this->company_id;
            $info->history = (new ApproveHistory())->getApproveHistory($info);
            $info->fileList = $this->getFileList($id,FILE_XZ);
            $info->date = $info->stop ? [$info->start,$info->stop] : $info->start;
            $roleid = $params['roleid'];

            $extend = $this->getInfoExtend($info,$roleid);

            $info->btn = $extend['btn'];

            $info->disabled = $extend['disabled'];

            $info->is_hidden = $extend['is_hidden'];

            $info->show_hzd = $roleid == 225 ? 1 : 0;


            return $info;
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    //编辑行政数据
    public function editBaoXiao($params)
    {
        try{
            DB::beginTransaction();
            $id = $params['id'];
            $roleid = $params['roleid'];
            $uid= $params['uid'];
            $newData = $params['newData'];
            $log = $this->checkDifferentData($newData,'xz');

            $date = $newData['date'];
            $start = is_array($date) ? $date[0] : $date;
            $stop = is_array($date) ? $date[1] : null;
            $limit_money = OALimit::getLimitMoney();
            if($newData['money'] > $limit_money) throw new \Exception('报销金额'.$newData['money'].'超出报销限额'.$limit_money);

            $updateData = [
                'updated_at'=>date('Y-m-d H:i:s'),
                'title'=>$newData['title'],
                'desc'=>$newData['desc'],
                'start'=>$start,
                'stop'=>$stop,
                'money'=>$newData['money'],
                'tracffic_from'=>$newData['tracffic_from'],
                'tracffic_to'=>$newData['tracffic_to'],
                'tracffic_type'=>$newData['tracffic_type'],
                'tracffic_area'=>$newData['tracffic_area'],
                'is_save'=>$params['is_save'],
            ];

            OAAdmin::query()->where('id',$id)->update($updateData);
            if ($log) {
                $logData = [
                    'note' => implode(';', $log),
                    'id' => $id,
                    'work_id' => $newData['work_id'],
                    'state' => 2,
                    'roleid' => $params['roleid'],
                    'uid' => $params['uid'],
                ];
                $this->saveShenPiLog($logData);
            }


            DB::commit();

            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //获取考勤数据
    public function getLoginList($params)
    {
        $query = OALogin::query();
        //用户
        if(isset($params['uid']) && !empty($params['uid'])) $query->where('uid',$params['uid']);
        //签到日期
        if(isset($params['date']) && !empty($params['date'])) $query->where('date',$params['date']);
        $list = $query->orderBy('date','DESC')->paginate($params['page_size'],['*'])->toArray();
        $common = (new CommonLogic())->getCommonData(['staff','position']);
        $staff_list = $common['staff'];
        $position_list = $common['position'];
        $staff_list = array_column($staff_list,'username','id');
        $position_list = array_column($position_list,'title','id');
        $list['staff_list'] = $staff_list;
        if(!$list['total']) return $list;
        $state_list = [1=>'正常',2=>'迟到',3=>'早退'];
        //dd($list['data']);
        foreach ($list['data'] as &$val){
            //dd($val);
            $val['username'] = $staff_list[$val['uid']];
            $val['state_start'] = $state_list[$val['state_start']] ?? '正常';
            $val['state_stop'] = $state_list[$val['state_stop']] ?? '正常';
            $val['srole'] = $position_list[$val['srole']] ?? '-';
            $val['erole'] = $position_list[$val['erole']] ?? '-';
            $val['sdesc'] = $val['sdesc'] ?? '无';
            $val['edesc'] = $val['edesc'] ?? '无';
            $val['sip'] = $val['sip'] ?? '未知';
            $val['eip'] = $val['eip'] ?? '未知';
        }
        //dd($list);
        return $list;

    }

}
